package com.inspire.springboot.service.imp;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.inspire.springboot.entity.TestInfo;
import com.inspire.springboot.service.WriteExcelService;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author :inspire
 * @date :Created in 2025/10/28 16:18
 * @description:
 * @modified By:inspire
 * @version:
 */
@Service
public class WriteExcelServiceImpl implements WriteExcelService {

    @Value("${excel.save.dir}")
    private String excelSaveDir;

    @Override
    public String writeTestReportToExcel(TestInfo testInfo) {
        // 创建保存目录
        File dir = new File(excelSaveDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 使用timestampStr作为文件名
        String fileName = testInfo.getTimestampStr() + ".xlsx";
        String filePath = excelSaveDir + File.separator + fileName;

        File excelFile = new File(filePath);
        ExcelWriter writer;

        // 检查文件是否存在
        if (excelFile.exists()) {
            // 文件存在，追加内容
            writer = ExcelUtil.getWriter(filePath);
            // 获取当前sheet的最后一行行号，然后在下一行追加数据
            Workbook workbook = writer.getWorkbook();
            Sheet sheet = workbook.getSheetAt(0);
            int lastRowNum = sheet.getLastRowNum();
            // 设置写入位置到最后一行的下一行
            writer.setCurrentRow(lastRowNum + 1);
        } else {
            // 文件不存在，创建新文件
            writer = new ExcelWriter(filePath);

            // 添加表头（新增字段放在最前面）
            List<String> headerRow = CollUtil.newArrayList(
                    "目标方法", "关联未覆盖分支", "测试目标", "前置条件", "用户角色", "测试步骤", "测试数据", "预期结果", "验证要点"
            );
            writer.writeHeadRow(headerRow);
        }

        // 添加数据行（新增字段放在最前面）
        List<String> dataRow = CollUtil.newArrayList(
                testInfo.getTargetMethod(),
                testInfo.getAssociateUncoveredBranches(),
                testInfo.getTestTarget(),
                testInfo.getFrontCondition(),
                testInfo.getUserRole(),
                testInfo.getTestSteps(),
                testInfo.getTestData(),
                testInfo.getExpectResult(),
                testInfo.getVerifyPoint()
        );
        writer.writeRow(dataRow);

        // 关闭writer并保存文件
        writer.close();

        return filePath;
    }
}
